#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/06/27
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from datetime import datetime
from project.flasky import db
from project.define import db_logger


DataName = "收费更次"
TableName = "app_charge_classes"


class ChargeClasses(db.Model):
    """
    收费更次
    """
    __tablename__ = TableName
    # 更次ID
    ClassesID = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
    # 收费处
    CashierName = db.Column(db.String(16), nullable=False)
    # 收费员
    UserName = db.Column(db.String(16), nullable=False)
    # 开始时间
    StartTime = db.Column(db.DateTime)
    # 现金支付
    Cash = db.Column(db.Float)
    # 银联支付
    UnionPay = db.Column(db.Float)
    # 澳门通
    MacauPay = db.Column(db.Float)
    # 支付宝
    AliPay = db.Column(db.Float)
    # 微信支付
    WeChatPay = db.Column(db.Float)
    # MPay
    MPay = db.Column(db.Float)
    # 收入
    Income = db.Column(db.Float)
    # 支出
    Expend = db.Column(db.Float)
    # 结束时间
    FinishTime = db.Column(db.DateTime)

    def __init__(self, **kwargs) -> None:
        super().__init__()
        self.CashierName = kwargs.get('CashierName')
        self.UserName = kwargs.get('UserName')
        self.StartTime = datetime.now()

    def to_dict(self):
        """
        转换键值对
        """
        def convert_data(name):
            val = getattr(self, name)
            if isinstance(val, datetime):
                return val.strftime('%Y/%m/%d %H:%M:%S')
            return val
            
        return dict([(c.name, convert_data(c.name)) for c in self.__table__.columns])

    @staticmethod
    def selected_data(**kwargs):
        """
        选中数据
        """
        classes_id = kwargs.get('ClassesID')
        if classes_id:
            return ChargeClasses.query.filter_by(ClassesID=classes_id).first()

    @staticmethod
    def column_name():
        """
        数据表标题
        """
        return {
            'ClassesID':'更次ID','CashierName':'收費處','UserName':'收費員','StartTime': '開始時間', 'Cash': '現金','UnionPay':'銀聯',
            'MacauPay':'澳門通','AliPay':'支付寶','WeChatPay':'微信支付','MPay':'MPay','Income':'總收入','FinishTime':'結算時間'}

    @staticmethod
    def generate_filters(**kwargs):
        """
        筛选器
        """
        filters = set()
        for k, v in kwargs.items():
            if v:
                if hasattr(ChargeClasses, k):
                    if k == 'CashierName':
                        filters.add(ChargeClasses.CashierName == v)
                    elif k == 'UserName':
                        filters.add(ChargeClasses.UserName == v)
                    elif k == 'StartTime':
                        if " - " in v:
                            start, end = [datetime.strptime(i, "%Y/%m/%d %H:%M:%S") for i in v.split(' - ') ]
                            filters.add(ChargeClasses.StartTime.between(start, end))
                    elif k == 'FinishTime':
                        if " - " in v:
                            start, end = [datetime.strptime(i, "%Y/%m/%d %H:%M:%S") for i in v.split(' - ') ]
                            filters.add(ChargeClasses.FinishTime.between(start, end))
        return filters

    @staticmethod
    def insert_data(**kwargs):
        """
        新增
        """
        try:
            kwargs.pop("id")
            r = ChargeClasses(**kwargs)
            db.session.add(r)
            db.session.commit()
            db_logger.debug(f"{TableName} => 新增{DataName}成功 ID:{r.ClassesID}：{kwargs}")
            return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 新增{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def delete_data(**kwargs):
        """
        删除
        """
        try:
            r = ChargeClasses.selected_data(**kwargs)
            if r:
                db.session.delete(r)
                db.session.commit()
                db_logger.debug(f"{TableName} => 删除{DataName}成功：{kwargs}")
                return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 删除{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def cashier_charge_class(**kwargs):
        """
        初始化
        """
        cashier_name = kwargs.get('CashierName')
        if cashier_name:
            rows = ChargeClasses.query.filter(
                ChargeClasses.CashierName==cashier_name,ChargeClasses.StartTime!=None,ChargeClasses.FinishTime==None).all()
            if rows:
                # 获取最新的更次
                r = rows[-1]
                return r.to_dict()
            else:
                return ChargeClasses.insert_data(**kwargs)

